//
//  QLPDFDrawingView.m
//  QLDemoProject
//
//  Created by Paramita on 2020/5/8.
//  Copyright © 2020 paramita. All rights reserved.
//

#import "QLPDFDrawingView.h"

#import "QLDrawPDFAnnotation.h"
#import "UIBezierPath+QLPDFDrawing.h"
#import "PDFPage+QLPDFDrawer.h"

@interface QLPDFDrawingView (){
    CGPoint currentPoint;
    CGPoint previousPoint1;
    CGPoint previousPoint2;
}

/// 添加的  anno数组
@property (strong, nonatomic) NSMutableArray *annoArray;
/// 撤销的  anno数组
@property (nonatomic, strong) NSMutableArray *bufferArray;
@property (nonatomic, strong) UIImage *image;
@property (strong, nonatomic) UIBezierPath *path;
@property (strong, nonatomic) PDFPage *currentPage;
@property (strong, nonatomic) QLDrawPDFAnnotation *currentAnnotaion;

@end

@implementation QLPDFDrawingView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self configure];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self configure];
    }
    return self;
}

- (void)configure {
    // set the default values for the public properties
    self.lineColor = kDefaultLineColor;
    self.lineWidth = kDefaultLineWidth;
    self.lineAlpha = kDefaultLineAlpha;
    
    // set the transparent background
    self.backgroundColor = UIColor.clearColor;
    // 通知
    [self addObserver];
}

- (void)addObserver {
    [[NSNotificationCenter defaultCenter] addObserverForName:@"PDFDrawRevocationNotification" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        
        if ([note.object isEqual:@(-1)]) {
            [self removeLastAnnotaion];
        } else if ([note.object isEqual:@(1)]) {
            [self addLastAnnotaion];
        }
    }];
}

/// 获取注释个数
- (NSInteger)getAnnoCount {
    return self.annoArray.count;
}

/// 是否需要保存
- (BOOL)isNeedSave {
    if (self.oldAnnoCount == self.addAnnoCount) {
        return NO;
    }
    return YES;
}

#pragma mark - 撤回
/// 点击撤回
- (void)removeLastAnnotaion {
    
    PDFAnnotation *annotaion = self.annoArray.lastObject;
    
    if (annotaion) {
        [annotaion.page removeAnnotation:annotaion];
        [self.annoArray removeObject:annotaion];
        self.addAnnoCount--;
        
        [self.bufferArray addObject:annotaion];
    }
}
#pragma mark - 反撤回
/// 点击反撤回
- (void)addLastAnnotaion {
    
    PDFAnnotation *annotaion = self.bufferArray.lastObject;
    
    if (annotaion) {
        [annotaion.page addAnnotation:annotaion];
        [self.annoArray addObject:annotaion];
        self.addAnnoCount++;
        
        [self.bufferArray removeObject:annotaion];
    }
}

/// 触摸撤回
- (void)removeAnnotaionAtPoint:(CGPoint)point page:(PDFPage*)page {
    
    PDFAnnotation *annotaion = [page annotationWithHitTest:point];
    if (annotaion) {
        [annotaion.page removeAnnotation:annotaion];
        [self.annoArray removeObject:annotaion];
        self.addAnnoCount--;
    }
}

#pragma mark - 触摸 UIResponder
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    UITouch *touch = touches.anyObject;
    previousPoint1 = [touch previousLocationInView:self];
    currentPoint = [touch locationInView:self];
    self.currentPage = [self.pdfView pageForPoint:previousPoint1 nearest:YES];
    CGPoint converPoiont = [self.pdfView convertPoint:previousPoint1 toPage:self.currentPage];
    self.path = [UIBezierPath new];
    [self.path moveToPoint:converPoiont];
    self.path.lineWidth = self.lineWidth;
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    UITouch *touch = touches.anyObject;
    previousPoint2 = previousPoint1;
    previousPoint1 = [touch previousLocationInView:self];
    currentPoint = [touch locationInView:self];
    
    /// pdf drawer
    CGPoint converddPreviousPoint2 = [self.pdfView convertPoint:previousPoint2 toPage:self.currentPage];
    CGPoint converedPreviousPoint1 = [self.pdfView convertPoint:previousPoint1 toPage:self.currentPage];
    CGPoint converedCurrnetPoint = [self.pdfView convertPoint:currentPoint toPage:self.currentPage];
    
//    NSLog(@"%.f  %.f  %.f", previousPoint2, previousPoint1, currentPoint);
//    NSLog(@"%.f  %.f  %.f", converddPreviousPoint2, converedPreviousPoint1, converedCurrnetPoint);
    
    if (self.action == QLPDFDrawingActionErase) {
        [self removeAnnotaionAtPoint:converedCurrnetPoint page:self.currentPage];
        return;
    }
    [self.path addPathPreviousPreviousPoint:converddPreviousPoint2 withPreviousPoint:converedPreviousPoint1 withCurrentPoint:converedCurrnetPoint];
    if (self.currentAnnotaion == nil) {
        CGRect bounds = [self.currentPage boundsForBox:self.pdfView.displayBox];
        NSLog(@"currentAnnotaion.bounds: %@", NSStringFromCGRect(bounds));
        self.currentAnnotaion = [[QLDrawPDFAnnotation alloc] initWithBounds:bounds forType:PDFAnnotationSubtypeInk withProperties:nil];
    }
    self.currentAnnotaion.color = self.lineColor;
    self.currentAnnotaion.path = self.path;
    [self.currentPage removeAnnotation:self.currentAnnotaion];
    [self.currentPage addAnnotation:self.currentAnnotaion];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
    if (!self.currentAnnotaion) {
        return;
    }
    
    [self.currentPage removeAnnotation:self.currentAnnotaion];
    
    CGRect bounds = CGRectMake(
                               self.path.bounds.origin.x - 5,
                               self.path.bounds.origin.y - 5,
                               self.path.bounds.size.width + 10,
                               self.path.bounds.size.height + 10
                               );
    UIBezierPath *finalPath = [UIBezierPath new];
    finalPath.CGPath = self.path.CGPath;
    finalPath.lineWidth = self.lineWidth;
    
    QLDrawPDFAnnotation *annotion = [[QLDrawPDFAnnotation alloc] initWithBounds:bounds forType:PDFAnnotationSubtypeInk withProperties:nil];
    annotion.color = self.lineColor;
    annotion.path = finalPath;
    [self.currentPage addAnnotation:annotion];
    [self.annoArray addObject:annotion];
    
    // 保存旧个数
    self.oldAnnoCount = self.addAnnoCount;
    
    self.addAnnoCount++;
    
    NSLog(@"addAnnotationCount: %ld", self.addAnnoCount);
    
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"" object:nil];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    // make sure a point is recorded
    [self touchesEnded:touches withEvent:event];
}


#pragma mark - 懒加载

- (NSMutableArray *)annoArray {
    if (!_annoArray) {
        _annoArray = [[NSMutableArray alloc] init];
    }
    return _annoArray;
}

- (NSMutableArray *)bufferArray {
    if (!_bufferArray) {
        _bufferArray = [[NSMutableArray alloc] init];
    }
    return _bufferArray;
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
